package com.action.mvc.auth.service;

import com.action.mvc.auth.dao.UserDao;
import com.action.mvc.auth.dao.UserRoleDao;
import com.action.mvc.auth.entity.User;
import com.action.mvc.auth.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * Created by Wuxiang on 2017/4/24.
 */
@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    UserRoleDao userRoleDao;

    public void addUser(User user){
        userDao.saveUser(user);
    }

    public void updateUser(User user){
        userDao.updateUser(user);
    }

    public void deleteById(Long id){
        userDao.deleteById(id);
    }

    public User getUser(String name, String password) {
        return userDao.getUser(name, password);
    }

    public List<User> getUsers(int page, int size) {
        return userDao.findUsers(page, size);
    }

    public List<User> getUsers(Collection<Long> ids) {
        return userDao.findUsersByIds(ids);
    }

    /**
     * 分页查询用户角色对应的关系
     * @param page
     * @param size
     * @return
     */
    public List<UserRole> getUserRoles(int page, int size){
        return userRoleDao.findUserRoles(page, size);
    }

    /**
     * 根据用户id 查询用户角色对应的关系
     * @param userId
     * @return
     */
    public List<UserRole> getUserRoleByUserId(Long userId){
        return userRoleDao.findUserRoleByUserId(userId);
    }

    /**
     * 保存用户角色对应的关系 （一对多 保存）
     * @param userId
     * @param roleIds
     */
    public void addUserRoles(Long userId, Long[] roleIds) {
        List<UserRole> userRoles = new ArrayList<>();
        Arrays.asList(roleIds).forEach(roleId->{
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoles.add(userRole);
        });
        userRoleDao.saveUserRoles(userRoles);
    }
}
